'use strict';
/**
 * @fileoverview 定时任务事件
 * @author sundbcn@gmail.com (sun debing)
 */

var _ = require('lodash');
var moment = require('moment');
var mongoose = require('mongoose');

/**
 * 定时信息
 */
var timerItemSchema = new mongoose.Schema({
    // 事件ID
    event_id: Number,
    // 触发时间
    trigger_tm: Number
});

/**
 * 定时事件
 */
var timeEventSchema = new mongoose.Schema({
    // 角色id
    role_id: {
        type: Number,
        required: true,
        unique: true,
        index: true
    },

    // 定时事件列表
    event_list: {
        type: [timerItemSchema],
        default: []
    },

    // 是否已排序
    sorted: {
        type: Number,
        default: 0
    }
});

/**
 * 查询到达触发时间的事件列表
 * @return {[type]} [description]
 */
timeEventSchema.methods.getReachEventList = function () {
    var self = this;
    var now_tm = moment().unix();
    var reach_list = [];
    _.forEach(self.event_list, function (item) {
        if (now_tm < item.trigger_tm) {
            return false;
        }

        reach_list.push(item);
    });

    return reach_list;
};

/**
 * 添加时间事件
 */
timeEventSchema.methods.addEvent = function (event_id, trigger_tm) {
    this.event_list.push({
        event_id: event_id,
        trigger_tm: trigger_tm
    });

    this.sorted = 0;
};

/**
 * 修改事件时间
 */
timeEventSchema.methods.modifyEvent = function (event_id, new_trigger_tm) {
    var self = this;
    _.forEach(self.event_list, function (evt) {
        if (evt.event_id === event_id) {
            evt.trigger_tm = new_trigger_tm;
            self.sorted = 0;
            return false;
        }
        return true;
    });
};

/**
 * 重排事件顺序
 */
timeEventSchema.methods.arrangeEvent = function () {
    if (!!this.sorted) {
        return;
    }
    this.event_list = _.orderBy(this.event_list, ['trigger_tm'], ['asc']);
    this.sorted = 1;
};

if (!timeEventSchema.options.toJSON) {
    timeEventSchema.options.toJSON = {};
}
/* jshint unused:false */
timeEventSchema.options.toJSON.transform = function (doc, ret) {
    delete ret._id;
    delete ret.__v;
};

mongoose.model('TimeEvent', timeEventSchema);
